package com.jn.zhinongbao.adapter;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.supportingagriculturaltreasures.bean.News;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.provider.AgriculturalContentProvider;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.textfield.TextInputEditText;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class PublishNewsActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_PICK = 1001;

    private TextInputEditText etTitle, etSummary;
    private EditText etContent; // 富文本编辑器
    private Spinner spinnerCategory;
    private ImageView ivImage;
    private Button btnSelectImage, btnPublish;

    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private User currentUser;
    private String selectedImagePath;

    // 分类选项
    private String[] categories = {"种植技术", "养殖技术", "农业资讯", "病虫防治"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_news);

        initViews();
        initData();
        setupSpinner();
        setupClickListeners();
        loadUserData();
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("发布农技文章");
        }

        etTitle = findViewById(R.id.et_title);
        etSummary = findViewById(R.id.et_summary);
        etContent = findViewById(R.id.et_content);
        spinnerCategory = findViewById(R.id.spinner_category);
        ivImage = findViewById(R.id.iv_image);
        btnSelectImage = findViewById(R.id.btn_select_image);
        btnPublish = findViewById(R.id.btn_publish);
    }

    private void initData() {
        databaseHelper = new DatabaseHelper(this);
        preferenceManager = new PreferenceManager(this);
    }

    private void setupSpinner() {
        android.widget.ArrayAdapter<String> adapter = new android.widget.ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);
    }

    private void setupClickListeners() {
        btnSelectImage.setOnClickListener(v -> selectImage());
        btnPublish.setOnClickListener(v -> publishNews());
    }

    private void loadUserData() {
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
            if (currentUser == null) {
                Toast.makeText(this, "用户信息获取失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_IMAGE_PICK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                Log.d("PublishNews", "Selected image URI: " + imageUri.toString());
                
                // 将图片复制到应用私有目录
                selectedImagePath = copyImageToAppDirectory(imageUri);
                if (selectedImagePath != null) {
                    Log.d("PublishNews", "Image saved to: " + selectedImagePath);
                    ivImage.setImageBitmap(BitmapFactory.decodeFile(selectedImagePath));
                    ivImage.setVisibility(View.VISIBLE);
                    Toast.makeText(this, "图片选择成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 将图片复制到应用私有目录
     */
    private String copyImageToAppDirectory(Uri uri) {
        try {
            // 创建应用私有目录下的images文件夹
            File imagesDir = new File(getFilesDir(), "images");
            if (!imagesDir.exists()) {
                imagesDir.mkdirs();
            }
            
            // 生成唯一的文件名
            String fileName = "news_image_" + System.currentTimeMillis() + ".jpg";
            File destFile = new File(imagesDir, fileName);
            
            // 复制文件
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                FileOutputStream outputStream = new FileOutputStream(destFile);
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                
                inputStream.close();
                outputStream.close();
                
                Log.d("PublishNews", "Image copied successfully to: " + destFile.getAbsolutePath());
                return destFile.getAbsolutePath();
            }
        } catch (IOException e) {
            Log.e("PublishNews", "Error copying image", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从URI获取真实文件路径（已废弃，保留作为备用）
     */
    private String getRealPathFromURI(Uri uri) {
        String result = null;
        try {
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                result = cursor.getString(columnIndex);
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 如果无法获取真实路径，尝试使用URI的路径部分
            result = uri.getPath();
        }
        return result;
    }

    private void publishNews() {
        if (!validateInput()) {
            return;
        }

        String title = etTitle.getText().toString().trim();
        String summary = etSummary.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        String category = categories[spinnerCategory.getSelectedItemPosition()];

        // 将普通文本转换为HTML格式
        String htmlContent = convertToHtml(content);

        // 创建新闻对象
        News news = new News(title, summary, htmlContent, selectedImagePath, 
                currentUser.getUsername(), currentUser.getId(), category);

        // 使用ContentProvider保存新闻
        ContentValues values = new ContentValues();
        values.put("title", news.getTitle());
        values.put("summary", news.getSummary());
        values.put("content", news.getContent());
        values.put("image_url", news.getImageUrl());
        values.put("author", news.getAuthor());
        values.put("author_id", news.getAuthorId());
        values.put("category", news.getCategory());
        values.put("view_count", 0);
        values.put("create_time", getCurrentTime());
        values.put("update_time", getCurrentTime());

        Uri resultUri = getContentResolver().insert(AgriculturalContentProvider.CONTENT_URI_NEWS, values);

        if (resultUri != null) {
            Toast.makeText(this, "文章发布成功！", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "文章发布失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean validateInput() {
        String title = etTitle.getText().toString().trim();
        String summary = etSummary.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (TextUtils.isEmpty(title)) {
            etTitle.setError("请输入标题");
            etTitle.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(summary)) {
            etSummary.setError("请输入摘要");
            etSummary.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(content)) {
            etContent.setError("请输入内容");
            etContent.requestFocus();
            return false;
        }

        return true;
    }

    private String convertToHtml(String plainText) {
        // 简单的文本转HTML，保留换行
        return "<html><body>" + 
               plainText.replace("\n", "<br/>") + 
               "</body></html>";
    }

    private String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.format(new Date());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 